from django import forms
from django.core.validators import RegexValidator
from users.models import Users
from django_redis import get_redis_connection


mobile_validator = RegexValidator(r"^1[3-9]\d{9}$","手机号码不正确")

class CheckImgCodeForm(forms.Form):
    """
    check img
    """
    mobile = forms.CharField(max_length=11,min_length=11,validators=[mobile_validator,],
                             error_messages={
                                 "max_length":"手机长度有误",
                                 "min_length":"手机长度有误",
                                 "required":"手机号码不能为空",
                             })
    img_code_id = forms.UUIDField(error_messages={"required":"图片uuid不能为空",})
    text = forms.CharField(max_length=4, min_length=4,
                           error_messages={"min_length": "图片验证码长度有误", "max_length": "图片验证码长度有误",
                                           "required": "图片验证码不能为空"})

    def clean_mobile(self):
        tel = self.cleaned_data.get("mobile")
        if Users.objects.filter(mobile=tel).count():
            raise forms.ValidationError("手机已被注册,请重新输入")
        return tel

    def clean(self):
        cleaned_data = super().clean()
        img_uuid = cleaned_data.get("img_code_id")
        mobile_num = cleaned_data.get("mobile")
        img_text = cleaned_data.get("text")

        # 1 获取图片验证码
        con_redis = get_redis_connection(alias='verify_codes')
        img_key = "img_{}".format(img_uuid).encode('utf8')

        real_image_code_origin = con_redis.get(img_key)
        con_redis.delete(img_key)

        real_image_code = real_image_code_origin.decode('utf8') if real_image_code_origin else None

        # 2 验证输入的图片验证码是否正确
        if (not real_image_code) or (img_text.upper() != real_image_code):
            raise forms.ValidationError("图片验证码不正确")

        # 3 判断60s内是否输入过
        sms_flag_fmt = "sms_flag_{}".format(mobile_num).encode("utf8")
        sms_flag =  con_redis.get(sms_flag_fmt)
        if sms_flag:
            raise forms.ValidationError("获取短信验证码过于频繁")

